package com.shop.framework.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.shop.framework.util.FileUtil;
import com.shop.framework.util.Logger;
import com.shop.framework.vo.FileItem;


@Controller
public class FileController {
    static class AttachmentFile {
        private String uuid;
        private String name;
        private long size;

        private CommonsMultipartFile fileData;

        public AttachmentFile() {
        }

        public AttachmentFile(String uuid, String name, long size) {
            this.uuid = uuid;
            this.name = name;
            this.size = size;
        }

        public String getUUID() {
            return uuid;
        }

        public void setUUID(String uuid) {
            this.uuid = uuid;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public long getSize() {
            return size;
        }

        public void setSize(long size) {
            this.size = size;
        }

        public CommonsMultipartFile getFileData() {
            return fileData;
        }

        public void setFileData(CommonsMultipartFile fileData) {
            this.fileData = fileData;
        }

        public static String generateUUID(String name) {
            return UUID.randomUUID().toString();
        }
    }

    @RequestMapping(method=RequestMethod.POST, value="/file")
    public String handleUpload(
                        Model model,
                        AttachmentFile file,
                        BindingResult result) throws IOException {

        file.setUUID(AttachmentFile.generateUUID(file.getFileData().getOriginalFilename()));
        
        file.setName(file.getFileData().getOriginalFilename());
        
        FileUtil.saveFile(file.getUUID(), file.getName(), file.getFileData().getBytes());

        Logger.getLogger().debug("File AttachementFile Name = " + file.getName());
        Logger.getLogger().debug("File AttachementFile Size = " + file.getSize());
        Logger.getLogger().debug("File Original Name = " + file.getFileData().getOriginalFilename());
        Logger.getLogger().debug("File Size = " + file.getFileData().getSize());
        
        model.addAttribute("file_id", file.getUUID());
        model.addAttribute("file_name", file.getFileData().getOriginalFilename());
        model.addAttribute("file_size", file.getFileData().getSize());
        model.addAttribute("file_path", "http://shop.kr:8080/pub/"+file.getUUID());
        
        return "file";
    }

    @RequestMapping(method=RequestMethod.DELETE, value="/file")
    public void handleDelete(@RequestParam("file_id") String file_id) throws IOException {
        FileUtil.decreaseRefCount(file_id);
    }

    @RequestMapping(method=RequestMethod.GET, value="/file")
    public String handleDownload(
                        HttpServletResponse res,
                        @RequestParam("file_id") String file_id) throws IOException {

        FileItem fileItem = FileUtil.touchAndGetFile(file_id);

        File file = new File(FileUtil.getPubDirectory() + fileItem.getAnex_fil_id_no());

        res.reset();
 
        res.setContentType("application/octet-stream");
        res.setContentLength((int)file.length());
        res.setHeader("Content-Transfer-Encoding", "binary");
        res.setHeader("Content-Disposition", "attachment;fileName=\"" + fileItem.getAnex_fil_nm() + "\"");

        OutputStream os = res.getOutputStream();
        FileInputStream fis = new FileInputStream(file);

        FileCopyUtils.copy(fis, os);

        fis.close();

        return "dummy";
    }

    @RequestMapping(method=RequestMethod.GET, value="/download")
    public String handleSimpleDownload(
                        HttpServletResponse res,
                        @RequestParam("file_type") String file_type,
                        @RequestParam("biz_id")    String biz_id,
                        @RequestParam("file_name") String file_name) throws IOException {

        String path = FileUtil.getPubDirectory();

        if ("form".equals(file_type)) {
            path += "forms/";
        }

        path += biz_id + "/" + file_name;

        File file = new File(path);

        res.reset();

        res.setContentType("application/octet-stream");
        res.setContentLength((int)file.length());
        res.setHeader("Content-Transfer-Encoding", "binary");
        res.setHeader("Content-Disposition", "attachment;fileName=\"" + file_name + "\"");

        OutputStream os = res.getOutputStream();
        FileInputStream fis = new FileInputStream(file);

        FileCopyUtils.copy(fis, os);

        fis.close();

        return "dummy";
    }
}
